package controller

import (
	_ "database/sql"
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"errors"
	"fmt"
	mssql "github.com/denisenkom/go-mssqldb"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"log"
	"net/http"
	"strconv"
	"time"
)

func GetClubDetail(ctx *gin.Context) {
	Cid := ctx.Query("cid")
	cid, _ := strconv.Atoi(Cid) //转化成整形
	Uid := ctx.Query("uid")
	uid, _ := strconv.Atoi(Uid)

	var ifShow = 0
	// 查询数据库
	DB := common.GetDB()
	DB = DB.Where("id=?", cid)

	var clubdetail model.Club

	//var clubdetail []model.Club
	err := DB.Find(&clubdetail).Error

	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}

	// 查询用户是否已存在该社团
	DB1 := common.GetDB()

	var existingRecord model.UserClub

	result := DB1.Table("user_clubs").Where("UID = ? AND Cid = ?", uid, cid).First(&existingRecord)
	if result.Error == nil {
		//若用户已经在该社团
		ifShow = 0
	} else if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		//若用户不在该社团
		ifShow = 1
	} else {
		// 查询时出错
		fmt.Println("查询出错:", result.Error)

		return
	}

	//获取社团相关文件
	// 查询数据库
	//DB1 := common.GetDB()
	//var file model.File
	//
	//err1 := DB1.Table("club_file").Where("FileCid = ?", cid).Find(&file).Error
	//
	//if err1 != nil {
	//	response.Response(ctx, http.StatusBadRequest, 400, nil, "获取文件发生错误，请重试")
	//	log.Println("err1:", err1)
	//	return
	//}

	//获取用户信息
	DB2 := common.GetDB()
	var user model.User

	err2 := DB2.Table("users").Where("uid = ?", uid).Find(&user).Error

	if err2 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "未找到用户信息")
		log.Println("err2:", err2)
		return
	}

	// 获取社团图片
	//db := common.GetDB()
	//var images []model.CImage

	//for _, club := range clubdetail {
	//	var tmp []model.CImage
	//	err1 := db.Where("Cid=? AND Main=?", club.Cid, 1).Find(&tmp).Error
	//	if err1 != nil {
	//		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
	//		log.Println("err1:", err1)
	//		return
	//	}
	//	images = append(images, tmp...)
	//}

	//判断社团是否被收藏
	//Db := common.GetDB()
	//var collected []int
	//for _, club := range clubdetail {
	//	var count int
	//	err2 := Db.Model(&model.ClubCollection{}).Where("Cid=? AND Uid =?", club.Cid, uid).Count(&count).Error
	//	if err2 != nil {
	//		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
	//		log.Println("err2:", err2)
	//		return
	//	}
	//	if count > 0 {
	//		collected = append(collected, 1)
	//	} else {
	//		collected = append(collected, 0)
	//	}
	//}

	// 返回查询结果
	//response.Success(ctx, gin.H{"club": clubdetail, "images": images, "collected": collected}, "获取成功")
	response.Success(ctx, gin.H{"club": clubdetail, "userinfo": user, "ifShow": ifShow}, "获取成功")
}

// 申请加入社团
func JoinClub(ctx *gin.Context) {

	// 获取 uid 字段的值
	uidStr := ctx.PostForm("uid") //申请人id

	// 将 uidStr 转换为 int 类型
	uid, err := strconv.Atoi(uidStr)
	if err != nil {
		// 处理转换错误，例如输出错误信息或者采取其他措施
		fmt.Println("转换失败:", err)
		// 在这里可以返回默认值或者适当的错误处理
	}

	// 获取 cid 字段的值
	cidStr := ctx.PostForm("cid")
	cid, err1 := strconv.Atoi(cidStr)
	if err1 != nil {
		// 处理转换错误，例如输出错误信息或者采取其他措施
		fmt.Println("转换失败:", err1)
		// 在这里可以返回默认值或者适当的错误处理
	}

	file := ctx.PostForm("file")
	reason := ctx.PostForm("reason")
	currentTime := time.Now() //申请时间
	const PermitState = 0     //状态为未审批

	// 得到所连接的数据库
	DB := common.GetDB()

	var clubinfo model.Club

	clubResult := DB.Table("clubs").Where("id = ?", cid).First(&clubinfo)

	if clubResult.Error != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", clubResult.Error)
		return
	}

	//将申请加入社团记录加入申请分表
	DB1 := common.GetDB()

	applyClub := model.ClubPermission{
		UID:     uid,
		PTime:   currentTime,
		PFile:   mssql.VarChar(file),
		Cid:     cid,
		PState:  PermitState,
		PReason: reason,
	}
	if err := DB1.Create(&applyClub).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save honor record"})
		return
	}
	joinclub_id := applyClub.PSid

	// 将申请信息加入总表
	var kind = 0

	Title := clubinfo.Cname + "加入社团申请"

	query1 := "INSERT INTO applies (apply_id,uid,kind,approval_state,title,apply_time,approver1,approver2)VALUES (?,?,?,?,?,?,?,?)"

	result1 := DB1.Exec(query1, joinclub_id, uid, kind, PermitState, Title, currentTime, clubinfo.LeaderID, clubinfo.AdminTeacherID)

	if result1.Error != nil {
		fmt.Println("执行 SQL 语句时发生错误:", result1.Error)
		// response错误提示给前端
		response.Response(ctx, http.StatusBadRequest, 400, nil, "申请加入社团发生错误，请重试")
	} else {
		// response成功提示给前端
		response.Response(ctx, http.StatusOK, 200, nil, "申请加入社团成功")
	}

}

// 获取一个社团的活动信息（社团详情页的活动信息展示）
func GetClubDetailAct(ctx *gin.Context) {
	Uid := ctx.Query("uid")
	uid, _ := strconv.Atoi(Uid)
	Cid := ctx.Query("cid")
	cid, _ := strconv.Atoi(Cid)

	// 查询数据库
	DB := common.GetDB()
	var activities []model.Activity

	err := DB.Where("State != ? AND Cid = ?", 0, cid).Find(&activities).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}

	//判断活动举办的社团名称
	dB := common.GetDB()

	var clubNames []string
	for _, activity := range activities {
		var clubs []model.Club
		err1 := dB.Where("id=?", activity.Cid).First(&clubs).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err1:", err1)
			return
		}
		for _, club := range clubs {
			clubNames = append(clubNames, club.Cname)
		}
	}

	//判断活动是否被收藏
	db := common.GetDB()
	var collected []int
	for _, activity := range activities {
		var count int
		err2 := db.Model(&model.ActivityCollection{}).Where("aid=? AND uid =?", activity.Aid, uid).Count(&count).Error
		if err2 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err2:", err2)
			return
		}
		if count > 0 {
			collected = append(collected, 1)
		} else {
			collected = append(collected, 0)
		}
	}

	// 返回查询结果
	response.Success(ctx, gin.H{"activities": activities, "clubNames": clubNames, "collected": collected}, "获取成功")
}

//// 收藏或取消收藏活动
//func CollectActivity(ctx *gin.Context) {
//	// 获取用户ID和活动ID,并转换为int
//	Uid := ctx.PostForm("uid")
//	uid, err := strconv.Atoi(Uid)
//	Aid := ctx.PostForm("aid")
//	aid, err1 := strconv.Atoi(Aid)
//	if err != nil {
//		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告！警告！")
//		return
//	}
//
//	if err1 != nil {
//		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告，警告！")
//		return
//	}
//
//	// 获取收藏状态
//	collected := ctx.PostForm("collected")
//
//	DB := common.GetDB()
//	if collected == "0" {
//		// 创建收藏记录
//		newcollection := model.ActivityCollection{
//			Uid: uid,
//			Aid: aid,
//		}
//
//		err2 := DB.Create(&newcollection).Error
//		// 将收藏记录保存到数据库
//		if err != nil {
//			response.Response(ctx, http.StatusInternalServerError, 400, nil, "收藏活动失败，请重试")
//			log.Println("err2", err2)
//			return
//		}
//		response.Response(ctx, http.StatusOK, 200, nil, "收藏活动成功")
//	} else {
//		// 删除收藏记录
//		var collection model.ActivityCollection
//		err3 := DB.Where("uid=? AND aid=?", uid, aid).Delete(&collection).Error
//		if err3 != nil {
//			response.Response(ctx, http.StatusInternalServerError, 400, nil, "取消收藏失败，请重试")
//			log.Println("err3", err3)
//			return
//		}
//		//  返回结果
//		response.Response(ctx, http.StatusOK, 200, nil, "取消收藏活动成功")
//	}
//}
//
//func JoinActivity(ctx *gin.Context) {
//	Uid := ctx.PostForm("uid")
//	uid, _ := strconv.Atoi(Uid)
//	Aid := ctx.PostForm("aid")
//	aid, _ := strconv.Atoi(Aid)
//	Time := ctx.PostForm("time")
//
//	db := common.GetDB()
//	activityApply := model.ActivityApply{}
//	//是否参加了该活动并在审批中
//	db.Where("UID=? AND id=? and Result=?", uid, aid, 0).First(&activityApply)
//	if activityApply.ID != 0 {
//		response.Success(ctx, gin.H{"permission": 1}, "您已报名参加")
//		return
//	}
//
//	//是否参加了该活动并报名成功
//	db.Where("UID=? AND id=? and Result=?", uid, aid, 1).First(&activityApply)
//	if activityApply.ID != 0 {
//		response.Success(ctx, gin.H{"permission": 2}, "您已报名成功")
//		return
//	}
//
//	// 还未参加活动或参与失败，查询对应的活动
//	var activity model.Activity
//	err1 := db.Where("id=?", aid).First(&activity).Error
//	if err1 != nil {
//		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
//	}
//
//	//如果仅社内成员参加，判断是否是社内成员
//	if activity.Permission == 1 {
//		var joinedClubs []model.UserClub
//		result := db.Where("Cid = ? AND UID = ?", activity.Cid, uid).Where("QuitTime IS NULL").Find(&joinedClubs)
//		if result.Error != nil {
//			response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询时发生错误!")
//			return
//		}
//		count := result.RowsAffected
//
//		//不是社内成员
//		if count == 0 {
//			response.Success(ctx, gin.H{"permission": 3}, "您没有权限参加该活动")
//			return
//		} else { //是社内成员:
//			applyTime, _ := time.Parse("2006-01-02 15:04:05", Time)
//			newActivityApply := model.ActivityApply{
//				Aid:       aid,
//				SID:       uid,
//				ApplyTime: applyTime,
//			}
//
//			err := db.Create(&newActivityApply).Error
//			if err != nil {
//				response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入活动申请失败，请重试！")
//				return
//			}
//
//			joinActivity_id := newActivityApply.ID
//			fmt.Println(joinActivity_id)
//			newApply := model.Apply{
//				Apply_ID:       joinActivity_id,
//				UserID:         uid,
//				Kind:           1,
//				Approval_State: 0,
//				Title:          activity.ATitle,
//				ApplyTime:      newActivityApply.ApplyTime,
//			}
//			err1 := db.Create(&newApply).Error
//			if err1 != nil {
//				response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入总申请失败，请重试！")
//				return
//			}
//			response.Success(ctx, gin.H{"permission": 0}, "报名成功")
//			return
//		}
//	} else {
//		tx := db.Begin()
//		if tx.Error != nil {
//			response.Response(ctx, http.StatusInternalServerError, 500, nil, "无法开始事务，请重试！")
//			return
//		}
//		applyTime, _ := time.Parse("2006-01-02 15:04:05", Time)
//		newActivityApply := model.ActivityApply{
//			Aid:       aid,
//			SID:       uid,
//			ApplyTime: applyTime,
//		}
//		err := tx.Create(&newActivityApply).Error
//		if err != nil {
//			tx.Rollback() // 回滚事务
//			response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入活动申请失败，请重试！")
//			return
//		}
//
//		joinActivity_id := newActivityApply.ID
//		newApply := model.Apply{
//			Apply_ID:       joinActivity_id,
//			UserID:         uid,
//			Kind:           1,
//			Approval_State: 0,
//			Title:          activity.ATitle,
//			ApplyTime:      newActivityApply.ApplyTime,
//		}
//		// 在事务中创建newApply
//		err1 := tx.Create(&newApply).Error
//		if err1 != nil {
//			tx.Rollback() // 回滚事务
//			response.Response(ctx, http.StatusBadRequest, 422, nil, "创建加入总申请失败，请重试！")
//			return
//		}
//		// 提交事务
//		err2 := tx.Commit().Error
//		if err2 != nil {
//			tx.Rollback() // 回滚事务
//			response.Response(ctx, http.StatusInternalServerError, 500, nil, "提交事务失败，请重试！")
//			return
//		}
//		response.Success(ctx, gin.H{"permission": 0}, "报名成功")
//		return
//	}
//}

// 收藏社团和取消收藏
//func CollectClub(ctx *gin.Context) {
//	// 获取用户ID和社团ID,并转换为int
//	Uid := ctx.PostForm("uid")
//	uid, err := strconv.Atoi(Uid)
//	Cid := ctx.PostForm("cid")
//	cid, err1 := strconv.Atoi(Cid)
//	if err != nil {
//		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告！警告！")
//		return
//	}
//
//	if err1 != nil {
//		response.Response(ctx, http.StatusBadRequest, 422, nil, "警告，警告！")
//		return
//	}
//
//	// 获取收藏状态
//	collected := ctx.PostForm("collected")
//
//	DB := common.GetDB()
//	if collected == "0" {
//		// 创建收藏记录
//		newcollection := model.ClubCollection{
//			UID: uid,
//			CID: cid,
//		}
//
//		err2 := DB.Create(&newcollection).Error
//		// 将收藏记录保存到数据库
//		if err != nil {
//			response.Response(ctx, http.StatusInternalServerError, 400, nil, "收藏社团失败，请重试")
//			log.Println("err2", err2)
//			return
//		}
//
//		response.Response(ctx, http.StatusOK, 200, nil, "收藏社团成功")
//	} else {
//		// 删除收藏记录
//		var collection model.ClubCollection
//		err3 := DB.Where("uid=? AND cid=?", uid, cid).Delete(&collection).Error
//		if err3 != nil {
//			response.Response(ctx, http.StatusInternalServerError, 400, nil, "取消收藏失败，请重试")
//			log.Println("err3", err3)
//			return
//		}
//
//		response.Response(ctx, http.StatusOK, 200, nil, "取消收藏社团成功")
//	}
//}
